﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WCell.RealmServer.Entities;
using WCell.Constants.Spells;
using WCell.RealmServer.Handlers;
using WCell.Constants;
using WCell.Constants.Updates;

namespace WCell.RealmServer.Spells.Auras.Misc
{
	public class CharmAuraHandler : AuraEffectHandler
	{
		protected internal override void CheckInitialize(WorldObject caster, Unit target, ref SpellFailedReason failReason)
		{
			if (!(caster is Unit))
			{
				failReason = SpellFailedReason.BadTargets;
			}
			else
			{
				var unit = (Unit)caster;
				if (unit.Charm != null)
				{
					failReason = SpellFailedReason.AlreadyHaveCharm;
				}
				else if (target.HasMaster)
				{
					failReason = SpellFailedReason.CantBeCharmed;
				}
				else if (unit.Level > EffectValue)
				{
					failReason = SpellFailedReason.Highlevel;
				}
				else if (unit.HasMaster)
				{
					failReason = SpellFailedReason.Charmed;
				}
				else if (unit is Character)
				{
					if (((Character)unit).ActivePet != null)
					{
						failReason = SpellFailedReason.AlreadyHaveSummon;
					}
				}
			}
		}

		protected internal override void Apply()
		{
			var caster = (Unit)m_aura.Caster;
			var target = m_aura.Auras.Owner;
			caster.Charm = target;
			target.Charmer = caster;

			if (caster is Character)
			{
				//((Character)caster).Bytes = new byte[] { 8, 0, 15, 0 };
				//caster.WriteSpontaneousOwnerUpdate((Character)caster,PlayerFields.PLAYER_FIELD_BYTES, UnitFields.CHARM);
			}

			var duration = m_aura.Duration;

			if (caster is Character && target is NPC)
			{
				((Character)caster).MakePet((NPC)target, duration);
			}
			else
			{
				caster.Enslave((NPC)target, duration);
			}
		}

		protected internal override void Remove(bool cancelled)
		{
			var caster = (Unit)m_aura.Caster;
			var target = m_aura.Auras.Owner;
			caster.Charm = null;
			target.Charmer = null;
			if (caster is Character)
			{
				if (((Character)caster).ActivePet == m_aura.Auras.Owner)
				{
					((Character)caster).ActivePet = null;
				}
			}
		}
	}
}
